package moodish.dummy;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import moodish.comm.ServerSideMessage.Type;
import moodish.comm.ServerComm;
import moodish.comm.ServerSideMessage;
import moodish.server.MoodishServer;

public class MoodishServerDummy implements MoodishServer {

	private ServerComm comm;
	private List<String> onlineUsers = new ArrayList<String>();
	private Map<String, List<String>> friendsList = new HashMap<String, List<String>>();

	@Override
	public void start(ServerComm serverComm) {
		this.comm = serverComm;
		comm.start();

		while(true){
			if(comm.hasNextMessage()){

				ServerSideMessage msg = serverComm.getNextMessage();

				if(msg.getType() == Type.CLIENT_CONNECTED){
					connected(msg);	
				}
				else if(msg.getType() == Type.CLIENT_DISCONNECTED){
					disconnected(msg);
				}
				else if(msg.getType() == Type.FRIENDSHIP){
					friendship(msg);
				}
				else if(msg.getType() == Type.UNFREINDSHIP){
					unfriendship(msg);
				}
				else if(msg.getType() == Type.MOODISH_MESSAGE){
					moodishMessage(msg);	
				}
			}
		}
	}

	private void connected(ServerSideMessage msg){
		for(String s: onlineUsers){
			comm.sendClientConnected(s, msg.getClientNickname());
		}

		onlineUsers.add(msg.getClientNickname());
	}

	private void disconnected(ServerSideMessage msg){
		for(String s: onlineUsers){
			comm.sendClientDisconnected(s, msg.getClientNickname());
		}

		onlineUsers.remove(msg.getClientNickname());
		friendsList.remove(msg.getClientNickname());

		Iterator<String> iterator = friendsList.keySet().iterator();
		while(iterator.hasNext()){
			String key = iterator.next();
			Iterator<String> iterator2 = friendsList.get(key).iterator();
			while(iterator2.hasNext()){
				String value = iterator2.next();
				if(value.equals(msg.getClientNickname())){
					iterator2.remove();
				}
			}
		}
	}

	private void friendship(ServerSideMessage msg){
		if(friendsList.containsKey(msg.getClientNickname())){
			friendsList.get(msg.getClientNickname()).add(msg.getPayload());
		}else{
			List<String> aux = new ArrayList<String>();
			aux.add(msg.getPayload());
			friendsList.put(msg.getClientNickname(), aux);
		}

		comm.sendNewFriendship(msg.getClientNickname(), msg.getPayload());
	}

	private void unfriendship(ServerSideMessage msg){
		Iterator<String> iterator = friendsList.get(msg.getClientNickname()).iterator();
		while(iterator.hasNext()){
			String value = iterator.next();
			if(value.equals(msg.getPayload())){
				iterator.remove();
			}
		}

		comm.sendClientDisconnected(msg.getClientNickname(), msg.getPayload());
	}

	private void moodishMessage(ServerSideMessage msg){
		for(String s: friendsList.get(msg.getClientNickname())){
			comm.sendMoodishMessage(msg.getClientNickname(), s, msg.getPayload());
		}
	}
}